package com.zhixun.mobile.modules.jiujiudevice;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.alipay.client.util.StringUtil;
import com.boxin.ims.modules.jiujiudevice.entity.JiuCashRecord;
import com.boxin.ims.modules.jiujiudevice.entity.JiuCompany;
import com.boxin.ims.modules.jiujiudevice.entity.JiuConsumeConfig;
import com.boxin.ims.modules.jiujiudevice.entity.JiuDevice;
import com.boxin.ims.modules.jiujiudevice.entity.JiuFreeTime;
import com.boxin.ims.modules.jiujiudevice.entity.JiuInk;
import com.boxin.ims.modules.jiujiudevice.entity.JiuInkRecord;
import com.boxin.ims.modules.jiujiudevice.entity.JiuOrderLog;
import com.boxin.ims.modules.jiujiudevice.entity.JiuOrderRecord;
import com.boxin.ims.modules.jiujiudevice.entity.JiuSn;
import com.boxin.ims.modules.jiujiudevice.service.JiuCashConfigService;
import com.boxin.ims.modules.jiujiudevice.service.JiuCashRecordService;
import com.boxin.ims.modules.jiujiudevice.service.JiuCompanyService;
import com.boxin.ims.modules.jiujiudevice.service.JiuConsumeConfigService;
import com.boxin.ims.modules.jiujiudevice.service.JiuDeviceService;
import com.boxin.ims.modules.jiujiudevice.service.JiuFreeTimeService;
import com.boxin.ims.modules.jiujiudevice.service.JiuInkRecordService;
import com.boxin.ims.modules.jiujiudevice.service.JiuInkService;
import com.boxin.ims.modules.jiujiudevice.service.JiuOrderLogService;
import com.boxin.ims.modules.jiujiudevice.service.JiuOrderRecordService;
import com.boxin.ims.modules.wechat.entity.JiuWechatMember;
import com.boxin.ims.modules.wechat.entity.MobileMessageRecorder;
import com.boxin.ims.modules.wechat.entity.WXPay;
import com.boxin.ims.modules.wechat.entity.WeChat;
import com.boxin.ims.modules.wechat.service.JiuWechatMemberService;
import com.boxin.ims.modules.wechat.service.MobileMessageRecorderService;
import com.boxin.ims.modules.wechat.service.WXPayService;
import com.boxin.ims.modules.wechat.service.WeChatService;
import com.boxin.ims.modules.wechat.utils.JsTicketUtils;
import com.boxin.ims.modules.wechat.utils.WechatCacheUtils;
import com.boxin.ims.modules.wechat.utils.WechatInterfaceUtils;
import com.boxin.ims.modules.wechat.utils.WechatUtils;
import com.phoenix.fly.util.StringUtils;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.mapper.JsonMapper;
import com.thinkgem.jeesite.common.utils.CacheUtils;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.JedisUtils;
import com.thinkgem.jeesite.common.utils.RequestUtil;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import com.wxpay.client.util.CommonUtil;
import com.wxpay.client.util.WxPayHelper;
import com.zhixun.mobile.common.utils.SMSUtils;
import com.zhixun.mobile.modules.base.web.BaseController;
import com.zhixun.mobile.modules.jiujiudevice.common.DeviceUtils;
import com.zhixun.mobile.modules.jiujiudevice.common.JsonResult;
import com.zhixun.mobile.modules.jiujiudevice.common.ResultCode;
import com.zhixun.mobile.modules.jiujiudevice.device.model.DataModel;
import com.zhixun.mobile.modules.jiujiudevice.device.model.FenduanModel;
import com.zhixun.mobile.modules.jiujiudevice.device.model.InkModel;
import com.zhixun.mobile.modules.jiujiudevice.device.model.OtherConsume;
import com.zhixun.mobile.modules.jiujiudevice.device.util.SocketUtils;

/**
 * 
 * @author dongchao
 * @date 2018年8月15日 下午4:29:54
 * @function
 *
 */

@Controller
@RequestMapping(value = Global.FRONT_PATH + "/jiujiudevice")
public class jiujiuMemberFrontController extends BaseController {

	private Logger log = LoggerFactory.getLogger(jiujiuMemberFrontController.class);

	public static final Long USER_ID = 2L;

	/**
	 * 限免全局配置
	 */
	public static final Long FREE_ID = 1L;
	@Autowired
	private MobileMessageRecorderService mobileMessageRecorderService;
	@Autowired
	private JiuWechatMemberService jiuWechatMemberService;
	@Autowired
	private JiuOrderRecordService jiuOrderRecordService;
	@Autowired
	private WXPayService wxPayService;
	@Autowired
	private WeChatService weChatService;
	@Autowired
	private JiuOrderLogService jiuOrderLogService;
	@Autowired
	private JiuInkService jiuInkService;
	/**
	 * 设备管理
	 */
	@Autowired
	private JiuDeviceService jiuDeviceService;

	/**
	 * 押金全局配置
	 */
	@Autowired
	private JiuCashConfigService jiuCashConfigService;
	/**
	 * 押金记录
	 */
	@Autowired
	private JiuCashRecordService jiuCashRecordService;

	@Autowired
	private JiuInkRecordService jiuInkRecordService;

	@Autowired
	private JiuConsumeConfigService jiuConsumeConfigService;

	/**
	 * 限免秒数
	 */
	@Autowired
	private JiuFreeTimeService jiuFreeTimeService;

	/**
	 * 
	 * @function: 得到登录页
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "login")
	public String login(HttpServletRequest request, HttpServletResponse response) {
		String openId = getOpenId("userinfo_openid", request);
		if (StringUtils.isEmpty(openId)) {
			// 拉取授权
			System.err.println("拉取了授权方法===》" + openId);
			String url = WechatUtils.getOAuthUrl("/jiujiudevice/login", USER_ID, request, response);
			return "redirect:" + url;
		}

		JiuWechatMember member = getMember(USER_ID, openId);
		if (member == null) {
			// 拉取授权
			System.err.println("拉取了授权方法===》" + openId);
			String url = WechatUtils.getOAuthUrl("/jiujiudevice/login", USER_ID, request, response);
			return "redirect:" + url;
		}
		return "modules/jiujiudeviceFront/login";
	}

	/**
	 * 用户中心 页面
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "usercenter")
	public String usercenter(HttpServletRequest request, HttpServletResponse response, Model model) {
		String openId = getOpenId("userinfo_openid", request);
		if (StringUtils.isEmpty(openId)) {
			// 拉取授权
			System.err.println("拉取了授权方法===》" + openId);
			String url = WechatUtils.getOAuthUrl("/jiujiudevice/usercenter", USER_ID, request, response);
			return "redirect:" + url;
		}

		JiuWechatMember member = getMember(USER_ID, openId);
		if (member == null) {
			// 拉取授权
			System.err.println("拉取了授权方法===》" + openId);
			String url = WechatUtils.getOAuthUrl("/jiujiudevice/usercenter", USER_ID, request, response);
			return "redirect:" + url;
		}

		if (StringUtils.isEmpty(member.getMobile())) {
			return "redirect:" + Global.FRONT_PATH + "/jiujiudevice/login";
		}
		// 获取用户押金记录 验证用户是否已经交押金
		JiuCashRecord cashRecordCondtion = new JiuCashRecord();
		cashRecordCondtion.setMemberId(member.getId());
		// 查询已付款的 【status = 1】
		cashRecordCondtion.setStatus(1);
		List<JiuCashRecord> cashlist = jiuCashRecordService.find(cashRecordCondtion);
		if (cashlist.size() == 0) {
			// 未交押金 跳转到 提示用户未交押金，并跳转押金支付页面
			model.addAttribute("noCashRecord", "noCashRecord");
		}
		getJsapiTicket(request, USER_ID);
		String message = RequestUtil.getString(request, "message");
		if (StringUtils.isNotEmpty(message)) {
			try {
				model.addAttribute("message", new String(message.getBytes("ISO8859-1"), "UTF-8"));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		model.addAttribute("member", member);
		return "modules/jiujiudeviceFront/usercenter";
	}

	/**
	 * 设备使用情况展示
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "usetime")
	public String usetime(HttpServletRequest request, HttpServletResponse response, Model model) {
		String openId = getOpenId("userinfo_openid", request);
		if (StringUtils.isEmpty(openId)) {
			// 拉取授权
			System.err.println("拉取了授权方法===》" + openId);
			String url = WechatUtils.getOAuthUrl("/jiujiudevice/usetime", USER_ID, request, response);
			return "redirect:" + url;
		}

		JiuWechatMember member = getMember(USER_ID, openId);
		if (member == null) {
			// 拉取授权
			System.err.println("拉取了授权方法===》" + openId);
			String url = WechatUtils.getOAuthUrl("/jiujiudevice/usetime", USER_ID, request, response);
			return "redirect:" + url;
		}

		if (StringUtils.isEmpty(member.getMobile())) {
			return "redirect:" + Global.FRONT_PATH + "/jiujiudevice/login";
		}

		// 获取用户正在使用的设备
		// 修改=----------------------------
		String deviceSn = RequestUtil.getString(request, "deviceSn");
		String orderNo = JedisUtils.get(JiuDevice.MEMBER_USE_DEVICE_CACHE_KEY + "_" + member.getId() + "_" + deviceSn);

		if (StringUtils.isEmpty(orderNo)) {
			return "redirect:" + Global.FRONT_PATH + "/jiujiudevice/usercenter";
		}
		JiuOrderRecord order = jiuOrderRecordService.getByOrderNo(orderNo);
		if (order == null) {
			return "redirect:" + Global.FRONT_PATH + "/jiujiudevice/usercenter";
		}
		JiuOrderLog orderLog = jiuOrderLogService.findByOrderNo(orderNo);
		if (orderLog == null) {
			return "redirect:" + Global.FRONT_PATH + "/jiujiudevice/usercenter";
		}
		/*
		 * //如果当前设备的order的endtime不为空的话，说明是断电 if(order.getStatus() == 0 &&
		 * order.getEndTime() != null){ return "redirect:" + Global.FRONT_PATH +
		 * "/jiujiudevice/usercenter"; }
		 */
		// 设置总的墨盒使用情况
		List<DataModel> dataList = inkMessage(orderLog.getDeviceSn());

		orderLog.setInkMessage(JSON.toJSONString(dataList));

		// 计算墨的总价
		double inktotal = 0d;
		if (dataList.size() > 0 && dataList != null) {
			for (int i = 0; i < dataList.size(); i++) {
				DataModel d = dataList.get(i);
				inktotal += d.getUseMoney();
			}
		}

		orderLog.setInkMoney(new BigDecimal(inktotal).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
		// 添加设备的类型
		String deviceType = (String) JedisUtils.getObject(JiuDevice.DEVICE_TYPE + order.getDeviceSn());
		model.addAttribute("deviceType", deviceType);

		// 修改
		// 获取用户押金记录 验证用户是否已经交押金
		JiuCashRecord cashRecordCondtion = new JiuCashRecord();
		cashRecordCondtion.setMemberId(member.getId());
		// 查询已付款的 【status = 1】
		cashRecordCondtion.setStatus(1);
		List<JiuCashRecord> cashlist = jiuCashRecordService.find(cashRecordCondtion);
		if (cashlist.size() == 0) {
			// 未交押金 跳转到 提示用户未交押金，并跳转押金支付页面
			model.addAttribute("noCashRecord", "noCashRecord");
		}
		getJsapiTicket(request, USER_ID);

		// 添加限免秒数，在此秒内不计数费用
		JiuFreeTime free = jiuFreeTimeService.get(FREE_ID);
		if (free != null) {
			model.addAttribute("free", free);
		}
		model.addAttribute("timer", System.currentTimeMillis() - order.getBeginTime().getTime());
		model.addAttribute("orderLog", orderLog);
		model.addAttribute("order", order);
		model.addAttribute("member", member);
		return "modules/jiujiudeviceFront/usetime";
	}

	/**
	 * 设备使用情况展示
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "updateUseTime")
	public String updateUseTime(HttpServletRequest request, HttpServletResponse response, Model model) {
		String sn = RequestUtil.getString(request, "sn");
		// 设置总的墨盒使用情况
		List<DataModel> dataList = inkMessage(sn);

		JiuOrderLog orderLog = new JiuOrderLog();
		orderLog.setInkMessage(JSON.toJSONString(dataList));

		// 计算墨的总价
		double inktotal = 0d;
		if (dataList.size() > 0 && dataList != null) {
			for (int i = 0; i < dataList.size(); i++) {
				DataModel d = dataList.get(i);
				inktotal += new BigDecimal(d.getUseMoney()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
			}
		}
		orderLog.setInkMoney(new BigDecimal(inktotal).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
		return JsonMapper.getInstance().toJson(orderLog);
	}

	/**
	 * 
	 * @function:
	 *            <p>
	 *            跳转到墨盒使用详情，不加定时器，显示结算页面的详情
	 *            </p>
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("payinkDetail")
	public String payinkDetail(HttpServletRequest request, HttpServletResponse response) {
		String sn = RequestUtil.getString(request, "sn");
		String orderNo = RequestUtil.getString(request, "orderNo");
		JiuDevice jiuDevice = jiuDeviceService.getBySn(sn);
		request.setAttribute("jiuDevice", jiuDevice);
		JiuOrderLog orderLog = jiuOrderLogService.findByOrderNo(orderNo);
		request.setAttribute("orderLog", orderLog);
		return "modules/jiujiudeviceFront/payinkDetail";
	}

	/**
	 * 
	 * @function:
	 *            <p>
	 *            跳转到墨盒使用详情
	 *            </p>
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("fenduanFrontDetail")
	public String fenduanFrontDetail(HttpServletRequest request, HttpServletResponse response) {
		String sn = RequestUtil.getString(request, "sn");
		JiuDevice jiuDevice = jiuDeviceService.getBySn(sn);
		request.setAttribute("jiuDevice", jiuDevice);
		return "modules/jiujiudeviceFront/xiaofeiDetail";
	}

	/***
	 * 前台分段显示数据的接口-用于查看设备的具体使用情况
	 */

	@RequestMapping("fenduanFrontData")
	@ResponseBody
	public String fenduanFrontData(HttpServletRequest request, HttpServletResponse response) {
		/** 计算 **/
		// 前端传入sn
		String sn = RequestUtil.getString(request, "sn");
		// 分段总的list
		List<FenduanModel<InkModel>> fen = new ArrayList<FenduanModel<InkModel>>();
		FenduanModel<InkModel> fm = new FenduanModel<InkModel>();
		List<InkModel> fenList = new ArrayList<InkModel>();

		// 统计总共有记录，目前是8路数据
		int t = 0;
		// 获得缓存的数据
		List<InkModel> someink = (List<InkModel>) JedisUtils.getObject(sn);
		// 单个设置

		if (someink != null && someink.size() > 0) {
			for (int i = 0; i < someink.size(); i++) {
				/*
				 * // 设置单价 List<DataModel> dList = someink.get(i).getDatalist();
				 * List<JiuInk> inkList = jiuInkService.findAll(); if (dList !=
				 * null) { for (int j = 0; j < dList.size(); j++) { DataModel
				 * data = dList.get(j); if(inkList != null){
				 * data.setFlag(inkList.get(j).getColor());
				 * data.setPrice(inkList.get(j).getPrice()); } } }
				 */
				// 分组
				if ((i + 1) < (someink.size())) {
					InkModel jir = someink.get(i);
					InkModel jir2 = someink.get(i + 1);
					if (jir.getInkStatus().equals(jir2.getInkStatus())) {
						fenList.add(jir);
					} else {
						fenList.add(jir);
						fm.setDatalist(fenList);
						fen.add(fm);
						fenList = new ArrayList<InkModel>();
						fm = new FenduanModel<InkModel>();
						continue;
					}
				} else {
					fenList.add(someink.get(someink.size() - 1));
					fm.setDatalist(fenList);
					// fm.setSubmoney(0d);
					fen.add(fm);
					fenList = new ArrayList<InkModel>();
					fm = new FenduanModel<InkModel>();
				}
			}
		}

		// 重新设置dataList，保证每一组只有一条数据
		List<InkModel> inkModelList = new ArrayList<InkModel>();
		// 得到设备的墨盒数据
		List<JiuInk> inkList = jiuInkService.findBySn(sn);

		if (fen != null) {
			for (int i = 0; i < fen.size(); i++) {
				FenduanModel<InkModel> f = fen.get(i);
				// double[] d = new double[10];
				// for (int k = 0; k < f.getDatalist().size(); k++) {

				// if (f.getDatalist().size() >= 2) {
				// 这个LIST是上一次的 8 路数据
				List<DataModel> dataList1 = f.getDatalist().get(0).getDatalist();
				// 这个是当前的8路数据
				// JSON.parseArray(f.getDatalist().get(k+1).getInkMessage(),DataModel.class);
				List<DataModel> dataList2 = f.getDatalist().get(f.getDatalist().size() - 1).getDatalist();
				t = dataList1.size();

				// 设置每组的一条数组吗，重新封装成dataList，赋给每一个分组
				// 路线，墨盒，单价，开始重量，结束重量，使用重量
				InkModel inkModel = new InkModel();
				List<DataModel> dataModel = new ArrayList<DataModel>();
				// 每组的最后一条的创建时间
				inkModel.setCreateTime(f.getDatalist().get(f.getDatalist().size() - 1).getCreateTime());
				inkModel.setInkStatus(f.getDatalist().get(f.getDatalist().size() - 1).getInkStatus());

				// 设置八路的总价,取8路
				double total = 0d;
				// 设置各组的list
				// List<Double> fenRouteList = new ArrayList<Double>();

				for (int k = 0; k < t; k++) {
					DataModel data = new DataModel();
					data.setId(inkList.get(k).getName().toString());
					data.setFlag(inkList.get(k).getColor());
					data.setPrice(inkList.get(k).getPrice());
					// 设置起始重量
					data.setPreValue(dataList1.get(k).getValue());
					// 设置当前重量
					data.setValue(dataList2.get(k).getValue());
					// 设置使用重量
					/*
					 * //如果当前的重量大于之前的重量，说明是误差数据，设为初始重量 if(data.getPreValue() <
					 * data.getValue()){ data.setValue(data.getPreValue()); }
					 */
					// 起始重量-当前重量
					if (data.getPreValue() < data.getValue()) {
						data.setUseValue(0.00);
					} else {
						data.setUseValue(data.getPreValue() - data.getValue());
					}

					// 各路的小计
					double value = new BigDecimal((data.getUseValue()) * inkList.get(k).getPrice())
							.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
					data.setUseMoney(value);
					dataModel.add(data);

					// 总计
					if (value > 0) {
						total += value;
					}
					if (value < 0) {
						value = 0;
					}
					// fenRouteList.add(value);
				}

				inkModel.setDatalist(dataModel);
				inkModelList.add(inkModel);
				f.setDatalist(inkModelList);
				inkModelList = new ArrayList<InkModel>();
				// f.setRouteList(fenRouteList);
				f.setSubmoney(new BigDecimal(total).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
				// }

				// }
			}
		}

		// 返回json字符串
		Map<String, Object> map = new HashMap<String, Object>();
		// 倒序排序
		Collections.reverse(fen);
		if (fen != null && fen.size() > 0) {
			map.put("r", true);
			// 倒序排列
			map.put("l", fen);
		} else {
			map.put("r", false);
		}
		return JsonMapper.toJsonString(map);
	}

	
	/***
	 * 
	 * @function:
	 *            <p>
	 *            获得包括下一条数据的墨盒的使用情况
	 *            </p>
	 * @return
	 */
	public List<DataModel> inkMessageAndNext(String sn) {

		/** 计算 **/
		// 分段总的list
		List<FenduanModel<InkModel>> fen = new ArrayList<FenduanModel<InkModel>>();
		FenduanModel<InkModel> fm = new FenduanModel<InkModel>();
		List<InkModel> fenList = new ArrayList<InkModel>();
		List<DataModel> dList = new ArrayList<DataModel>();
		// 获得墨盒的配置
		List<JiuInk> inkList = jiuInkService.findBySn(sn);

		// 八路总的值
		double[] dall = new double[10];
		// 统计总共有记录，目前是8路数据
		int t = 0;
		
		// 获得缓存的数据
		List<InkModel> someink = (List<InkModel>) JedisUtils.getObject(sn);
		//获得缓存的下一条的数据
		if (JedisUtils.exists(JiuDevice.DEVICE_CUR_DATA + "_" + sn)) {
			InkModel inkModel = (InkModel) JedisUtils.getObject(JiuDevice.DEVICE_CUR_DATA + "_" + sn);
			someink.add(inkModel);
		}
		
		// 单个设置
		if (someink != null && someink.size() > 0) {
			for (int i = 0; i < someink.size(); i++) {
				if ((i + 1) < (someink.size())) {
					InkModel jir = someink.get(i);
					InkModel jir2 = someink.get(i + 1);
					if (jir.getInkStatus().equals(jir2.getInkStatus())) {
						fenList.add(jir);
					} else {
						fenList.add(jir);
						fm.setDatalist(fenList);
						fen.add(fm);
						fenList = new ArrayList<InkModel>();
						fm = new FenduanModel<InkModel>();
						continue;
					}
				} else {
					fenList.add(someink.get(someink.size() - 1));
					fm.setDatalist(fenList);
					// fm.setSubmoney(0d);
					fen.add(fm);
					fenList = new ArrayList<InkModel>();
					fm = new FenduanModel<InkModel>();
				}
			}
		}
		if (fen != null) {
			for (int i = 0; i < fen.size(); i++) {
				FenduanModel<InkModel> f = fen.get(i);
				double[] d = new double[10];
				for (int k = 0; k < f.getDatalist().size(); k++) {

					if (f.getDatalist().size() >= 2) {
						// 这个LIST是上一次的 8 路数据
						List<DataModel> dataList1 = f.getDatalist().get(0).getDatalist();
						// 这个是当前的8路数据
						// JSON.parseArray(f.getDatalist().get(k+1).getInkMessage(),DataModel.class);
						List<DataModel> dataList2 = f.getDatalist().get(f.getDatalist().size() - 1).getDatalist();
						// 用上一次的8路数据 分别减去当前的8路数据
						double[] totalValue = chuliData(dataList1, dataList2, d);
						t = dataList1.size();
						// 设置八路的总价,取8路
						double total = 0d;

						for (int l = 0; l < t; l++) {

							total += (totalValue[l]) * inkList.get(l).getPrice();
						}

						f.setSubmoney(new BigDecimal(total).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
					}

				}
				// 获得总八路的值,放置出现负值，波动数据
				for (int k = 0; k < t; k++) {
					if (d[k] >= 0) {
						dall[k] += d[k];
					}

				}
			}
		}
		// 设置设备的json数据格式
		// 用来计算总的使用金额和使用的重量
		for (int x = 0; x < t; x++) {
			DataModel data = new DataModel();
			data.setId((x + 1) + "");
			data.setUseValue(dall[x]);
			if (inkList != null) {
				data.setPrice(inkList.get(x).getPrice());
				data.setFlag(inkList.get(x).getColor());
				/*
				 * data.setValue(value); data.setPreValue();
				 */
				// g变为kg
				data.setUseMoney(new BigDecimal((data.getUseValue()) * data.getPrice())
						.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
			}
			dList.add(data);
		}
		return dList;
	}

	
	/***
	 * 
	 * @function:
	 *            <p>
	 *            获得墨盒的使用情况
	 *            </p>
	 * @return
	 */
	public List<DataModel> inkMessage(String sn) {

		/** 计算 **/
		// 分段总的list
		List<FenduanModel<InkModel>> fen = new ArrayList<FenduanModel<InkModel>>();
		FenduanModel<InkModel> fm = new FenduanModel<InkModel>();
		List<InkModel> fenList = new ArrayList<InkModel>();
		List<DataModel> dList = new ArrayList<DataModel>();
		// 获得墨盒的配置
		List<JiuInk> inkList = jiuInkService.findBySn(sn);

		// 八路总的值
		double[] dall = new double[10];
		// 统计总共有记录，目前是8路数据
		int t = 0;
		// 获得缓存的数据
		List<InkModel> someink = (List<InkModel>) JedisUtils.getObject(sn);
		// 单个设置
		if (someink != null && someink.size() > 0) {
			for (int i = 0; i < someink.size(); i++) {
				if ((i + 1) < (someink.size())) {
					InkModel jir = someink.get(i);
					InkModel jir2 = someink.get(i + 1);
					if (jir.getInkStatus().equals(jir2.getInkStatus())) {
						fenList.add(jir);
					} else {
						fenList.add(jir);
						fm.setDatalist(fenList);
						fen.add(fm);
						fenList = new ArrayList<InkModel>();
						fm = new FenduanModel<InkModel>();
						continue;
					}
				} else {
					fenList.add(someink.get(someink.size() - 1));
					fm.setDatalist(fenList);
					// fm.setSubmoney(0d);
					fen.add(fm);
					fenList = new ArrayList<InkModel>();
					fm = new FenduanModel<InkModel>();
				}
			}
		}
		if (fen != null) {
			for (int i = 0; i < fen.size(); i++) {
				FenduanModel<InkModel> f = fen.get(i);
				double[] d = new double[10];
				for (int k = 0; k < f.getDatalist().size(); k++) {

					if (f.getDatalist().size() >= 2) {
						// 这个LIST是上一次的 8 路数据
						List<DataModel> dataList1 = f.getDatalist().get(0).getDatalist();
						// 这个是当前的8路数据
						// JSON.parseArray(f.getDatalist().get(k+1).getInkMessage(),DataModel.class);
						List<DataModel> dataList2 = f.getDatalist().get(f.getDatalist().size() - 1).getDatalist();
						// 用上一次的8路数据 分别减去当前的8路数据
						double[] totalValue = chuliData(dataList1, dataList2, d);
						t = dataList1.size();
						// 设置八路的总价,取8路
						double total = 0d;

						for (int l = 0; l < t; l++) {

							total += (totalValue[l]) * inkList.get(l).getPrice();
						}

						f.setSubmoney(new BigDecimal(total).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
					}

				}
				// 获得总八路的值,放置出现负值，波动数据
				for (int k = 0; k < t; k++) {
					if (d[k] >= 0) {
						dall[k] += d[k];
					}

				}
			}
		}
		// 设置设备的json数据格式
		// 用来计算总的使用金额和使用的重量
		for (int x = 0; x < t; x++) {
			DataModel data = new DataModel();
			data.setId((x + 1) + "");
			data.setUseValue(dall[x]);
			if (inkList != null) {
				data.setPrice(inkList.get(x).getPrice());
				data.setFlag(inkList.get(x).getColor());
				/*
				 * data.setValue(value); data.setPreValue();
				 */
				// g变为kg
				data.setUseMoney(new BigDecimal((data.getUseValue()) * data.getPrice())
						.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
			}
			dList.add(data);
		}
		return dList;
	}

	/***
	 * 
	 * @function:
	 *            <p>
	 *            每一组开始使用量-最后剩余量
	 *            </p>
	 * @param dataList1
	 * @param dataList2
	 * @param d
	 * @return
	 */
	public static double[] chuliData(List<DataModel> dataList1, List<DataModel> dataList2, double[] d) {
		// TODO Auto-generated method stub
		for (int i = 0; i < dataList1.size(); i++) {
			// 如果d[i] == 0说明就是某一路的初始值
			d[i] = dataList1.get(i).getValue() - dataList2.get(i).getValue();
		}
		return d;
	}

	/**
	 * 取消设备使用
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "quitUseDevice")
	public String quitUseDevice(HttpServletRequest request, HttpServletResponse response, Model model) {
		String openId = getOpenId("userinfo_openid", request);
		if (StringUtils.isEmpty(openId)) {
			// 拉取授权
			System.err.println("拉取了授权方法===》" + openId);
			String url = WechatUtils.getOAuthUrl("/jiujiudevice/quitUseDevice", USER_ID, request, response);
			return "redirect:" + url;
		}

		JiuWechatMember member = getMember(USER_ID, openId);
		if (member == null) {
			// 拉取授权
			System.err.println("拉取了授权方法===》" + openId);
			String url = WechatUtils.getOAuthUrl("/jiujiudevice/quitUseDevice", USER_ID, request, response);
			return "redirect:" + url;
		}

		if (StringUtils.isEmpty(member.getMobile())) {
			return "redirect:" + Global.FRONT_PATH + "/jiujiudevice/login";
		}

		// 获取用户正在使用的设备
		// 修改------------------------------------------
		String deviceSn = RequestUtil.getString(request, "deviceSn");
		String orderNo = JedisUtils.get(JiuDevice.MEMBER_USE_DEVICE_CACHE_KEY + "_" + member.getId() + "_" + deviceSn);
		if (StringUtils.isNotEmpty(orderNo)) {
			JedisUtils.del(JiuDevice.MEMBER_USE_DEVICE_CACHE_KEY + "_" + member.getId() + "_" + deviceSn);
		}

		return "redirect:" + Global.FRONT_PATH + "/jiujiudevice/usercenter";
	}

	/**
	 * 使用设备
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "usedevice")
	public synchronized String usedevice(HttpServletRequest request, HttpServletResponse response, Model model,
			RedirectAttributes redirectAttributes) {
		String openId = getOpenId("userinfo_openid", request);
		if (StringUtils.isEmpty(openId)) {
			// 拉取授权
			System.err.println("拉取了授权方法===》" + openId);
			String url = WechatUtils.getOAuthUrl("/jiujiudevice/usedevice", USER_ID, request, response);
			return "redirect:" + url;
		}

		JiuWechatMember member = getMember(USER_ID, openId);
		if (member == null) {
			// 拉取授权
			System.err.println("拉取了授权方法===》" + openId);
			String url = WechatUtils.getOAuthUrl("/jiujiudevice/usedevice", USER_ID, request, response);
			return "redirect:" + url;
		}

		if (StringUtils.isEmpty(member.getMobile())) {
			return "redirect:" + Global.FRONT_PATH + "/jiujiudevice/login";
		}

		// 获取用户押金记录 验证用户是否已经交押金
		JiuCashRecord cashRecordCondtion = new JiuCashRecord();
		cashRecordCondtion.setMemberId(member.getId());
		// 查询已付款的 【status = 1】
		cashRecordCondtion.setStatus(1);
		List<JiuCashRecord> cashlist = jiuCashRecordService.find(cashRecordCondtion);
		if (cashlist.size() == 0) {
			// 未交押金 跳转到 提示用户未交押金，并跳转押金支付页面
			writeMessageAndRedirect(request, response, "您还未支付押金，不能使用设备，点击确定后跳转到押金支付",
					Global.FRONT_PATH + "/jiujiudevice/jiaoyajin");
			return null;
			// return "redirect:" + Global.FRONT_PATH +
			// "/jiujiudevice/jiaoyajin";
		}

		// 验证用户是否有未支付订单
		List<JiuOrderRecord> orderList = jiuOrderRecordService.queryUnpaidOrderByMember(member.getId());
		if (orderList.size() > 0) {
			writeMessageAndRedirect(request, response, "您还有待支付订单，点击确定后将自动跳转到支付页面",
					Global.FRONT_PATH + "/jiujiudevice/pay");
			return null;
			// 有未支付订单。跳转到支付页面
			// return "redirect:" + Global.FRONT_PATH + "/jiujiudevice/pay";
		}

		// 查找设备信息
		// System.out.println("usedevice========================>sn==========>"+deviceSn);
		String deviceSn = RequestUtil.getString(request, "deviceSn");

		JiuDevice device = jiuDeviceService.getBySn(deviceSn);
		if (null == device) {
			writeMessageAndRedirect(request, response, "该设备没有注册，不能使用", Global.FRONT_PATH + "/jiujiudevice/usercenter");
			return null;
		}

		// 如果设备不是存在的或者断电的，直接清除用户的订单，直接返回usercenter

		if (!JedisUtils.exists(JiuSn.DEVICE_EXSIT + "_" + deviceSn)) {
			// 设备不存在，直接返回usercenter
			writeMessageAndRedirect(request, response, "设备无法使用,请确定设备是否存在",
					Global.FRONT_PATH + "/jiujiudevice/usercenter");
			return null;

		}

		// 如果是用户正在使用的设备， 则直接显示 使用信息页
		// 修改===================================》
		String o = JedisUtils.get(JiuDevice.MEMBER_USE_DEVICE_CACHE_KEY + "_" + member.getId() + "_" + deviceSn);
		if (StringUtils.isNotEmpty(o)) {
			return "redirect:" + Global.FRONT_PATH + "/jiujiudevice/usetime?deviceSn=" + deviceSn + "&r="
					+ Math.random();
		}
		// 验证是否有其他用户正在使用该设备。
		Object _orderLog = JedisUtils.getObject(JiuDevice.DEVICE_RUNTIME_KEY_PREFIX + deviceSn);
		if (_orderLog != null) {

			model.addAttribute("isUsed", "use");
			writeMessageAndRedirect(request, response, "已有其他用户正在使用此设备", Global.FRONT_PATH + "/jiujiudevice/usercenter");
			return null;
			// redirectAttributes.addAttribute("message","已有其他用户正在使用此设备。你不是使用人。");
			// return "redirect:" + Global.FRONT_PATH +
			// "/jiujiudevice/usercenter";
		}

		// 得到设备最新的数据
		// 返回设备信息最新的墨盒数据
		// 查询墨盒的配置列表
		List<JiuInk> jiuInkList = jiuInkService.findBySn(deviceSn);
		if (JedisUtils.exists(JiuDevice.DEVICE_CUR_DATA + "_" + deviceSn)) {
			InkModel inkModel = (InkModel) JedisUtils.getObject(JiuDevice.DEVICE_CUR_DATA + "_" + deviceSn);
			List<DataModel> inkList = inkModel.getDatalist();
			if (inkList != null) {
				if (jiuInkList != null) {
					for (int i = 0; i < jiuInkList.size(); i++) {
						DataModel d = inkList.get(i);
						d.setFlag(jiuInkList.get(i).getColor());
						d.setPrice(jiuInkList.get(i).getPrice());
					}
				}
			}
			model.addAttribute("inkList", inkList);
		}

		// 添加限免秒数，在此秒内不计数费用
		JiuFreeTime free = jiuFreeTimeService.get(FREE_ID);
		if (free != null) {
			model.addAttribute("free", free);
		}
		model.addAttribute("device", device);
		model.addAttribute("member", member);
		return "modules/jiujiudeviceFront/usetime";
	}

	/**
	 * 打开设备
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "opendevice")
	public synchronized String opendevice(HttpServletRequest request, HttpServletResponse response, Model model,
			RedirectAttributes redirectAttributes) {
		String openId = getOpenId("userinfo_openid", request);
		if (StringUtils.isEmpty(openId)) {
			// 拉取授权
			System.err.println("拉取了授权方法===》" + openId);
			String url = WechatUtils.getOAuthUrl("/jiujiudevice/usedevice", USER_ID, request, response);
			return "redirect:" + url;
		}

		JiuWechatMember member = getMember(USER_ID, openId);
		if (member == null) {
			// 拉取授权
			System.err.println("拉取了授权方法===》" + openId);
			String url = WechatUtils.getOAuthUrl("/jiujiudevice/usedevice", USER_ID, request, response);
			return "redirect:" + url;
		}

		if (StringUtils.isEmpty(member.getMobile())) {
			return "redirect:" + Global.FRONT_PATH + "/jiujiudevice/login";
		}

		// 获取用户押金记录 验证用户是否已经交押金
		JiuCashRecord cashRecordCondtion = new JiuCashRecord();
		cashRecordCondtion.setMemberId(member.getId());
		// 查询已付款的 【status = 1】
		cashRecordCondtion.setStatus(1);
		List<JiuCashRecord> cashlist = jiuCashRecordService.find(cashRecordCondtion);
		if (cashlist.size() == 0) {
			// 未交押金 跳转到 提示用户未交押金，并跳转押金支付页面
			return "redirect:" + Global.FRONT_PATH + "/jiujiudevice/jiaoyajin";
		}
		// 验证用户是否有未支付订单
		List<JiuOrderRecord> noPayOrderList = jiuOrderRecordService.queryUnpaidOrderByMember(member.getId());
		if (noPayOrderList.size() != 0) {
			// 有未支付的订单。 跳转到支付页面
			return "redirect:" + Global.FRONT_PATH + "/jiujiudevice/pay";
		}

		// 如果用户有正在使用的设备， 则直接显示 使用信息页
		// 修改--------------------------
		// 寻找设备码
		String deviceSn = RequestUtil.getString(request, "deviceSn");
		String o = JedisUtils.get(JiuDevice.MEMBER_USE_DEVICE_CACHE_KEY + "_" + member.getId() + "_" + deviceSn);
		if (StringUtils.isNotEmpty(o)) {
			return "redirect:" + Global.FRONT_PATH + "/jiujiudevice/usetime?deviceSn=" + deviceSn + "&r="
					+ Math.random();
		}

		JiuDevice device = jiuDeviceService.getBySn(deviceSn);

		// 验证是否有其他用户正在使用该设备。
		Object _orderLog = JedisUtils.getObject(JiuDevice.DEVICE_RUNTIME_KEY_PREFIX + deviceSn);
		if (_orderLog != null) {
			redirectAttributes.addAttribute("message", "有其他用户正在使用该设备");
			return "redirect:" + Global.FRONT_PATH + "/jiujiudevice/usetime";
		}

		// 创建使用记录，并缓存使用设备
		Date beginTime = new Date(System.currentTimeMillis());
		JiuOrderRecord order = new JiuOrderRecord();
		order.setDelFlag(JiuOrderRecord.DEL_NO);

		String orderNo = JiuOrderRecord.generateOrderNo();
		order.setOrderNo(orderNo);
		order.setBeginTime(beginTime);

		order.setCompanyId(device.getCompanyId());
		order.setCompanyName(device.getCompanyName());

		order.setMemberId(member.getId());
		order.setMemberMobile(member.getMobile());
		order.setMemberOpenId(member.getOpenId());

		order.setStatus(JiuOrderRecord.STATUS_NO_PAY);

		order.setDeviceSn(device.getSn());
		order.setDeviceName(device.getName());
		order.setAmount(0d);
		order = jiuOrderRecordService.save(order);

		JiuOrderLog orderLog = new JiuOrderLog();
		orderLog.setOrderNo(orderNo);
		orderLog.setOrderId(order.getId());
		orderLog.setDeviceBeginTime(order.getBeginTime());
		orderLog.setDevicePrice(device.getPrice());
		orderLog.setDeviceSn(device.getSn());
		orderLog.setInkMoney(0d);
		orderLog.setDeviceAmount(0d);
		/** 其他消费使用情况开始 */
		List<OtherConsume> otherConsume = new ArrayList<OtherConsume>();
		// 拼接其他消费的json
		List<JiuConsumeConfig> jiuConsumeConfig = jiuConsumeConfigService.findAll();
		if (jiuConsumeConfig != null) {
			for (int i = 0; i < jiuConsumeConfig.size(); i++) {
				OtherConsume other = new OtherConsume();
				JiuConsumeConfig jiu = jiuConsumeConfig.get(i);
				other.setName(jiu.getName());
				other.setPrice(jiu.getPrice());
				otherConsume.add(other);

			}
		}
		orderLog.setOtherMessage(JSON.toJSONString(otherConsume));

		/** 其他消费使用情况结束 */
		orderLog = jiuOrderLogService.save(orderLog);

		// 调用接口打开设备 ，并返回 设备使用信息 返回设备信息
		JedisUtils.setObject(JiuDevice.DEVICE_RUNTIME_KEY_PREFIX + deviceSn, orderLog, 0);
		// 缓存用户当前使用的所有设备。
		String keyresult = JedisUtils.set(JiuDevice.MEMBER_USE_DEVICE_CACHE_KEY + "_" + member.getId() + "_" + deviceSn,
				order.getOrderNo(), 0);

		// 缓存生成的所有的订单，断电的时候线程处理
		JedisUtils.set(JiuDevice.MEMBER_USE_DEVICE_CACHE_KEY + "_" + deviceSn, order.getOrderNo(), 0);
		if (keyresult == null) {
			log.error("用户【{}】【{}】保存当前使用设备到redis失败，订单号【{}】", member.getName(), member.getOpenId(), order.getOrderNo());
		}
		model.addAttribute("member", member);
		model.addAttribute("orderLog", orderLog);
		model.addAttribute("device", device);
		model.addAttribute("order", order);

		// 添加扫一扫的jsap
		getJsapiTicket(request, USER_ID);
		// 添加设备的类型
		String deviceType = (String) JedisUtils.getObject(JiuDevice.DEVICE_TYPE + deviceSn);
		model.addAttribute("deviceType", deviceType);
		// 添加限免秒数，在此秒内不计数费用
		JiuFreeTime free = jiuFreeTimeService.get(FREE_ID);
		if (free != null) {
			model.addAttribute("free", free);
		}
		return "modules/jiujiudeviceFront/usetime";
	}

	/**
	 * 关闭设备
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "closedevice")
	public synchronized String closedevice(HttpServletRequest request, HttpServletResponse response,
			RedirectAttributes redirectAttributes) {
		String openId = getOpenId("userinfo_openid", request);
		if (StringUtils.isEmpty(openId)) {
			// 拉取授权
			System.err.println("拉取了授权方法===》" + openId);
			String url = WechatUtils.getOAuthUrl("/jiujiudevice/closedevice", USER_ID, request, response);
			return "redirect:" + url;
		}

		JiuWechatMember member = getMember(USER_ID, openId);
		if (member == null) {
			// 拉取授权
			System.err.println("拉取了授权方法===》" + openId);
			String url = WechatUtils.getOAuthUrl("/jiujiudevice/closedevice", USER_ID, request, response);
			return "redirect:" + url;
		}

		if (StringUtils.isEmpty(member.getMobile())) {
			log.error("用户【{}】【{}】未绑定手机号访问closedevice接口", member.getNickname(), member.getOpenId());
			return "redirect:" + Global.FRONT_PATH + "/jiujiudevice/login";
		}

		// 修改------------
		String deviceSn = RequestUtil.getString(request, "deviceSn");
		String orderNo = JedisUtils.get(JiuDevice.MEMBER_USE_DEVICE_CACHE_KEY + "_" + member.getId() + "_" + deviceSn);
		if (StringUtils.isEmpty(orderNo)) {
			redirectAttributes.addAttribute("message", "错误的操作，没有正在使用的设备");
			log.error("用户【{}】【{}】关闭设备失败。没有获取到缓存中的设备", member.getNickname(), member.getOpenId());
			return "redirect:" + Global.FRONT_PATH + "/jiujiudevice/usercenter";
		}

		JiuOrderRecord order = jiuOrderRecordService.getByOrderNo(orderNo);
		if (order == null) {
			redirectAttributes.addAttribute("message", "错误的操作，设备获取失败");
			log.error("用户【{}】【{}】关闭设备失败。【订单记录获取失败】", member.getNickname(), member.getOpenId());
			return "redirect:" + Global.FRONT_PATH + "/jiujiudevice/usercenter";
		}

		JiuOrderLog orderLog = jiuOrderLogService.findByOrderNo(orderNo);
		if (orderLog == null) {
			redirectAttributes.addAttribute("message", "错误的操作，设备获取失败");
			log.error("用户【{}】【{}】关闭设备失败。【订单日志获取失败】", member.getNickname(), member.getOpenId());
			return "redirect:" + Global.FRONT_PATH + "/jiujiudevice/usercenter";
		}

		JiuDevice device = jiuDeviceService.getBySn(order.getDeviceSn());
		if (device == null) {
			redirectAttributes.addAttribute("message", "错误的操作，设备获取失败");
			log.error("用户【{}】【{}】关闭设备失败。【设备获取失败】设备编号SN【{}】", member.getNickname(), member.getOpenId(),
					order.getDeviceSn());
			return "redirect:" + Global.FRONT_PATH + "/jiujiudevice/usercenter";
		}

		if (orderLog.getDeviceUseTime() != null) {
			redirectAttributes.addAttribute("message", "错误的操作，设备已关闭");
			log.error("用户【{}】【{}】关闭设备失败。【设备已关闭】设备编号SN【{}】", member.getNickname(), member.getOpenId(),
					order.getDeviceSn());
			return "redirect:" + Global.FRONT_PATH + "/jiujiudevice/usercenter";
		}
		// 关闭设备

		// 关闭后 计算并记录使用 使用时间 金额等。

		// 计算设备使用时间
		Date deviceEndTime = new Date(System.currentTimeMillis());

		Long useTime = deviceEndTime.getTime() - orderLog.getDeviceBeginTime().getTime();

		// 计算秒数，如果秒数未超出免费秒数，计费为0
		Long useSec = DeviceUtils.calUseSec(useTime);
		// 得到设置免费秒数
		JiuFreeTime freeTime = jiuFreeTimeService.get(FREE_ID);
		Long useMin = 0L;
		if (useSec <= freeTime.getMin()) {
			useMin = 0L;
		} else {
			useMin = DeviceUtils.calUseMin(useTime);
		}

		String useStr = DeviceUtils.formatUseTime(useTime);
		orderLog.setDeviceEndTime(deviceEndTime);
		orderLog.setDeviceUseTime(useTime);
		orderLog.setDeviceUseMin(useMin);
		orderLog.setDeviceUseTimeStr(useStr);

		// 计算设备所需金额 使用金额 = 设备单价*分钟数；
		Double amount = device.getPrice() * useMin;
		orderLog.setDeviceAmount(amount);

		/** 其他消费使用情况开始 */
		List<OtherConsume> otherConsume = new ArrayList<OtherConsume>();
		// 拼接其他消费的json
		List<JiuConsumeConfig> jiuConsumeConfig = jiuConsumeConfigService.findAll();
		Double otherTotalMoney = 0d;
		for (int i = 0; i < jiuConsumeConfig.size(); i++) {
			OtherConsume other = new OtherConsume();
			JiuConsumeConfig jiu = jiuConsumeConfig.get(i);
			other.setName(jiu.getName());
			other.setPrice(jiu.getPrice());
			// 计算其他消费金额 单价*分钟
			other.setValue(jiu.getPrice() * orderLog.getDeviceUseMin());
			otherTotalMoney += other.getValue();
			otherConsume.add(other);
		}
		orderLog.setOtherMessage(JSON.toJSONString(otherConsume));
		/** 其他消费使用情况结束 */
		jiuOrderLogService.save(orderLog);

		// 设备+其他消费的总价
		order.setAmount(amount + otherTotalMoney);
		order.setEndTime(deviceEndTime);
		jiuOrderRecordService.save(order);
		// 关闭设备（发布关闭设备命令）
		/*
		 * JedisUtils.setObject(JiuDevice.DEVICE_RUNTIME_KEY_PREFIX +
		 * orderLog.getDeviceSn(), orderLog,0);
		 */
		JedisUtils.del(JiuDevice.DEVICE_RUNTIME_KEY_PREFIX + orderLog.getDeviceSn());

		// 删除当前sn的数据缓存
		// JedisUtils.del(orderLog.getDeviceSn());

		// 如果订单金额为0 说明没有消费，由线程删除改订单
		if (order != null && order.getAmount() == 0d) {
			JedisUtils.del(JiuDevice.MEMBER_USE_DEVICE_CACHE_KEY + "_" + member.getId() + "_" + deviceSn);
			// 删除当前sn的数据缓存
			JedisUtils.del(orderLog.getDeviceSn());
			return "redirect:" + Global.FRONT_PATH + "/jiujiudevice/usercenter";
		}

		request.getSession().setAttribute("deviceSn", orderLog.getDeviceSn());
		return "redirect:" + Global.FRONT_PATH + "/jiujiudevice/timePage";
	}

	
	
	/**
	 * 跳转定时支付页面
	 */
	@RequestMapping("timePage")
	public String timePage(HttpServletRequest request, HttpServletResponse response){
		String deviceSn = (String) request.getSession().getAttribute("deviceSn");
		//设置设备公司和设备名称
		if(StringUtils.isNotEmpty(deviceSn)){
			JiuDevice jiuDevice = jiuDeviceService.getBySn(deviceSn);
            request.setAttribute("jiuDevice",jiuDevice);
		}
		return "modules/jiujiudeviceFront/time";
	}
	
	/**
	 * 存储最新的数据
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "saveAll")
	public synchronized String saveAll(HttpServletRequest request, HttpServletResponse response,
			RedirectAttributes redirectAttributes) {
		String openId = getOpenId("userinfo_openid", request);
		if (StringUtils.isEmpty(openId)) {
			// 拉取授权
			System.err.println("拉取了授权方法===》" + openId);
			String url = WechatUtils.getOAuthUrl("/jiujiudevice/closedevice", USER_ID, request, response);
			return "redirect:" + url;
		}

		JiuWechatMember member = getMember(USER_ID, openId);
		if (member == null) {
			// 拉取授权
			System.err.println("拉取了授权方法===》" + openId);
			String url = WechatUtils.getOAuthUrl("/jiujiudevice/closedevice", USER_ID, request, response);
			return "redirect:" + url;
		}

		if (StringUtils.isEmpty(member.getMobile())) {
			log.error("用户【{}】【{}】未绑定手机号访问closedevice接口", member.getNickname(), member.getOpenId());
			return "redirect:" + Global.FRONT_PATH + "/jiujiudevice/login";
		}

		// 修改------------
		String deviceSn = RequestUtil.getString(request, "deviceSn");
		String orderNo = JedisUtils.get(JiuDevice.MEMBER_USE_DEVICE_CACHE_KEY + "_" + member.getId() + "_" + deviceSn);
		if (StringUtils.isEmpty(orderNo)) {
			redirectAttributes.addAttribute("message", "错误的操作，没有需要支付的设备");
			log.error("用户【{}】【{}】关闭设备失败。没有获取到缓存中的设备", member.getNickname(), member.getOpenId());
			return "redirect:" + Global.FRONT_PATH + "/jiujiudevice/usercenter";
		}

		JiuOrderRecord order = jiuOrderRecordService.getByOrderNo(orderNo);
		if (order == null) {
			redirectAttributes.addAttribute("message", "错误的操作，设备获取失败");
			log.error("用户【{}】【{}】关闭设备失败。【订单记录获取失败】", member.getNickname(), member.getOpenId());
			return "redirect:" + Global.FRONT_PATH + "/jiujiudevice/usercenter";
		}

		JiuOrderLog orderLog = jiuOrderLogService.findByOrderNo(orderNo);
		if (orderLog == null) {
			redirectAttributes.addAttribute("message", "错误的操作，设备获取失败");
			log.error("用户【{}】【{}】关闭设备失败。【订单日志获取失败】", member.getNickname(), member.getOpenId());
			return "redirect:" + Global.FRONT_PATH + "/jiujiudevice/usercenter";
		}

		JiuDevice device = jiuDeviceService.getBySn(order.getDeviceSn());
		if (device == null) {
			redirectAttributes.addAttribute("message", "错误的操作，设备获取失败");
			log.error("用户【{}】【{}】关闭设备失败。【设备获取失败】设备编号SN【{}】", member.getNickname(), member.getOpenId(),
					order.getDeviceSn());
			return "redirect:" + Global.FRONT_PATH + "/jiujiudevice/usercenter";
		}

		/** 计算墨盒使用的各路总金额 */
		// 设置总的墨盒使用情况
		List<DataModel> dataList = inkMessageAndNext(orderLog.getDeviceSn());
		orderLog.setInkMessage(JSON.toJSONString(dataList));

		// 计算墨的总价
		double inktotal = 0d;
		if (dataList.size() > 0 && dataList != null) {
			for (int i = 0; i < dataList.size(); i++) {
				DataModel d = dataList.get(i);
				inktotal += new BigDecimal(d.getUseMoney()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
			}
		}
		orderLog.setInkMoney(new BigDecimal(inktotal).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());

		jiuOrderLogService.save(orderLog);

		// 设备+墨盒的总价+其他消费的总价
		order.setAmount(orderLog.getInkMoney() + order.getAmount());
		jiuOrderRecordService.save(order);

		// 保存数据库
		save(orderLog);

		JedisUtils.del(JiuDevice.MEMBER_USE_DEVICE_CACHE_KEY + "_" + member.getId() + "_" + order.getDeviceSn());
		// 删除当前sn的数据缓存
		JedisUtils.del(orderLog.getDeviceSn());

		return "redirect:" + Global.FRONT_PATH + "/jiujiudevice/pay";
	}

	/***
	 * 后台、前台分段显示数据的接口-用于查看设备的具体使用情况，关闭设备后
	 */

	@RequestMapping("fenduanData")
	@ResponseBody
	public String fenduanData(HttpServletRequest request, HttpServletResponse response) {
		// 获得sn和orderNo的值
		String sn = RequestUtil.getString(request, "sn");

		String orderNo = RequestUtil.getString(request, "orderNo");
		// 获取墨盒记录表
		List<JiuInkRecord> inkRecord = jiuInkRecordService.findByOrderNoAndDeviceSn(orderNo, sn);
		// 分段总的list，******返回的json对象
		List<FenduanModel<JiuInkRecord>> fen = new ArrayList<FenduanModel<JiuInkRecord>>();

		// 每一个list对应一个新的fm对象
		FenduanModel<JiuInkRecord> fm = new FenduanModel<JiuInkRecord>();
		List<JiuInkRecord> fenList = new ArrayList<JiuInkRecord>();
		// 单个设置fm的分组
		if (inkRecord != null) {
			for (int i = 0; i < inkRecord.size(); i++) {
				if ((i + 1) < (inkRecord.size())) {
					JiuInkRecord jir = inkRecord.get(i);
					JiuInkRecord jir2 = inkRecord.get(i + 1);
					if (jir.getInkStatus().equals(jir2.getInkStatus())) {
						fenList.add(jir);
					} else {
						fenList.add(jir);
						fm.setDatalist(fenList);
						fen.add(fm);
						fenList = new ArrayList<JiuInkRecord>();
						fm = new FenduanModel<JiuInkRecord>();
						continue;
					}
				} else {
					fenList.add(inkRecord.get(inkRecord.size() - 1));
					fm.setDatalist(fenList);
					fen.add(fm);
					fenList = new ArrayList<JiuInkRecord>();
					fm = new FenduanModel<JiuInkRecord>();
				}
			}
		}

		// 遍历各个fm的每一个list，求得每一组的合计数s
		int t = 0;
		// 重新设置dataList，保证每一组只有一条数据
		List<JiuInkRecord> inkModelList = new ArrayList<JiuInkRecord>();
		// 得到八路的墨盒数据
		List<JiuInk> inkList = jiuInkService.findBySn(sn);
		if (fen != null) {
			for (int i = 0; i < fen.size(); i++) {
				FenduanModel<JiuInkRecord> f = fen.get(i);
				// 这个LIST是上一次的 8 路数据
				List<DataModel> dataList1 = JSON.parseArray(f.getDatalist().get(0).getInkMessage(), DataModel.class);
				// 这个是当前的8路数据
				// JSON.parseArray(f.getDatalist().get(k+1).getInkMessage(),DataModel.class);
				List<DataModel> dataList2 = JSON
						.parseArray(f.getDatalist().get(f.getDatalist().size() - 1).getInkMessage(), DataModel.class);
				// 得到有几路的值
				t = dataList1.size();

				// 设置每组的一条数组吗，重新封装成dataList，赋给每一个分组
				// 路线，墨盒，单价，开始重量，结束重量，使用重量
				JiuInkRecord jiuInkRecord = new JiuInkRecord();
				List<DataModel> dataModel = new ArrayList<DataModel>();
				// 每组的最后一条的创建时间
				jiuInkRecord.setCreateTime(f.getDatalist().get(f.getDatalist().size() - 1).getCreateTime());
				jiuInkRecord.setInkStatus(f.getDatalist().get(f.getDatalist().size() - 1).getInkStatus());

				// 设置八路的总价,取8路
				double total = 0d;
				// 设置各组的list
				List<Double> fenRouteList = new ArrayList<Double>();

				for (int k = 0; k < t; k++) {
					DataModel data = new DataModel();
					data.setId(inkList.get(k).getName().toString());
					data.setFlag(inkList.get(k).getColor());
					data.setPrice(inkList.get(k).getPrice());
					// 设置起始重量
					data.setPreValue(dataList1.get(k).getValue());
					// 设置当前重量
					data.setValue(dataList2.get(k).getValue());
					// 设置使用重量
					// 如果当前的重量大于之前的重量，说明是误差数据，设为初始重量
					/*
					 * if(data.getPreValue() < data.getValue()){
					 * data.setValue(data.getPreValue()); }
					 */
					// 起始重量-当前重量
					if (data.getPreValue() < data.getValue()) {
						data.setUseValue(0.00);
					} else {
						data.setUseValue(data.getPreValue() - data.getValue());
					}

					dataModel.add(data);

					double value = new BigDecimal((data.getUseValue()) * inkList.get(k).getPrice())
							.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
					if (value > 0) {
						total += value;
					}
					if (value < 0) {
						value = 0;
					}
					fenRouteList.add(value);
				}

				jiuInkRecord.setInkMessage(JSON.toJSONString(dataModel));
				inkModelList.add(jiuInkRecord);
				f.setDatalist(inkModelList);
				inkModelList = new ArrayList<JiuInkRecord>();
				f.setRouteList(fenRouteList);
				f.setSubmoney(new BigDecimal(total).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
			}
		}
		// 返回json字符串
		Map<String, Object> map = new HashMap<String, Object>();
		if (fen != null && fen.size() > 0) {
			map.put("r", true);
			map.put("l", fen);
		} else {
			map.put("r", false);
		}
		return JsonMapper.toJsonString(map);
	}

	@RequestMapping("payInkDetailData")
	@ResponseBody
	public String payInkDetailData(HttpServletRequest request, HttpServletResponse response) {
		// 获得sn和orderNo的值
		String sn = RequestUtil.getString(request, "sn");

		String orderNo = RequestUtil.getString(request, "orderNo");
		// 获取墨盒记录表
		List<JiuInkRecord> inkRecord = jiuInkRecordService.findByOrderNoAndDeviceSn(orderNo, sn);
		// 分段总的list，******返回的json对象
		List<FenduanModel<JiuInkRecord>> fen = new ArrayList<FenduanModel<JiuInkRecord>>();

		// 每一个list对应一个新的fm对象
		FenduanModel<JiuInkRecord> fm = new FenduanModel<JiuInkRecord>();
		List<JiuInkRecord> fenList = new ArrayList<JiuInkRecord>();
		// 单个设置fm的分组
		if (inkRecord != null) {
			for (int i = 0; i < inkRecord.size(); i++) {
				if ((i + 1) < (inkRecord.size())) {
					JiuInkRecord jir = inkRecord.get(i);
					JiuInkRecord jir2 = inkRecord.get(i + 1);
					if (jir.getInkStatus().equals(jir2.getInkStatus())) {
						fenList.add(jir);
					} else {
						fenList.add(jir);
						fm.setDatalist(fenList);
						fen.add(fm);
						fenList = new ArrayList<JiuInkRecord>();
						fm = new FenduanModel<JiuInkRecord>();
						continue;
					}
				} else {
					fenList.add(inkRecord.get(inkRecord.size() - 1));
					fm.setDatalist(fenList);
					fen.add(fm);
					fenList = new ArrayList<JiuInkRecord>();
					fm = new FenduanModel<JiuInkRecord>();
				}
			}
		}

		// 遍历各个fm的每一个list，求得每一组的合计数s
		int t = 0;
		// 重新设置dataList，保证每一组只有一条数据
		List<JiuInkRecord> inkModelList = new ArrayList<JiuInkRecord>();
		// 得到八路的墨盒数据
		List<JiuInk> inkList = jiuInkService.findBySn(sn);
		if (fen != null) {
			for (int i = 0; i < fen.size(); i++) {
				FenduanModel<JiuInkRecord> f = fen.get(i);
				// 这个LIST是上一次的 8 路数据
				List<DataModel> dataList1 = JSON.parseArray(f.getDatalist().get(0).getInkMessage(), DataModel.class);
				// 这个是当前的8路数据
				// JSON.parseArray(f.getDatalist().get(k+1).getInkMessage(),DataModel.class);
				List<DataModel> dataList2 = JSON
						.parseArray(f.getDatalist().get(f.getDatalist().size() - 1).getInkMessage(), DataModel.class);
				// 得到有几路的值
				t = dataList1.size();

				// 设置每组的一条数组吗，重新封装成dataList，赋给每一个分组
				// 路线，墨盒，单价，开始重量，结束重量，使用重量
				JiuInkRecord jiuInkRecord = new JiuInkRecord();
				List<DataModel> dataModel = new ArrayList<DataModel>();
				// 每组的最后一条的创建时间
				jiuInkRecord.setCreateTime(f.getDatalist().get(f.getDatalist().size() - 1).getCreateTime());
				jiuInkRecord.setInkStatus(f.getDatalist().get(f.getDatalist().size() - 1).getInkStatus());

				// 设置八路的总价,取8路
				double total = 0d;
				// 设置各组的list
				List<Double> fenRouteList = new ArrayList<Double>();

				for (int k = 0; k < t; k++) {
					DataModel data = new DataModel();
					data.setId(inkList.get(k).getName().toString());
					data.setFlag(inkList.get(k).getColor());
					data.setPrice(inkList.get(k).getPrice());
					// 设置起始重量
					data.setPreValue(dataList1.get(k).getValue());
					// 设置当前重量
					data.setValue(dataList2.get(k).getValue());
					// 设置使用重量
					// 如果当前的重量大于之前的重量，说明是误差数据，设为初始重量
					if (data.getPreValue() < data.getValue()) {
						data.setUseValue(0.00);
					} else {
						// 起始重量-当前重量
						data.setUseValue(data.getPreValue() - data.getValue());
					}
					dataModel.add(data);

					double value = new BigDecimal((data.getUseValue()) * inkList.get(k).getPrice())
							.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
					if (value > 0) {
						total += value;
					}
					if (value < 0) {
						value = 0;
					}
					fenRouteList.add(value);
				}

				jiuInkRecord.setInkMessage(JSON.toJSONString(dataModel));
				inkModelList.add(jiuInkRecord);
				f.setDatalist(inkModelList);
				inkModelList = new ArrayList<JiuInkRecord>();
				f.setRouteList(fenRouteList);
				f.setSubmoney(new BigDecimal(total).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
			}
		}
		// 返回json字符串
		Map<String, Object> map = new HashMap<String, Object>();
		if (fen != null && fen.size() > 0) {
			map.put("r", true);
			map.put("l", fen);
		} else {
			map.put("r", false);
		}
		return JsonMapper.toJsonString(map);
	}

	/***
	 * 
	 * @function:
	 *            <p>
	 *            关闭设备后存储数据库-获得墨盒的使用情况
	 *            </p>
	 * @return
	 */
	public void save(JiuOrderLog orderLog) {

		double[] d = new double[10];
		// 获得缓存的数据
		List<InkModel> someink = (List<InkModel>) JedisUtils.getObject(orderLog.getDeviceSn());
		//获得缓存的下一条的数据
		if (JedisUtils.exists(JiuDevice.DEVICE_CUR_DATA + "_" + orderLog.getDeviceSn())) {
				InkModel inkModel = (InkModel) JedisUtils.getObject(JiuDevice.DEVICE_CUR_DATA + "_" + orderLog.getDeviceSn());
				someink.add(inkModel);
		}
		// 用来计算总的使用金额和使用的重量
		// 设置数据库数据
		if (someink != null && someink.size() > 0) {
			for (int i = 0; i < someink.size(); i++) {
				// 存储设备记录表中
				JiuInkRecord jiuInkRecord = new JiuInkRecord();

				jiuInkRecord.setInkStatus(someink.get(i).getInkStatus());
				jiuInkRecord.setSn(someink.get(i).getSn());
				// 获得设备的名称
				JiuDevice jiuDevice = jiuDeviceService.getBySn(jiuInkRecord.getSn());
				String snName = jiuDevice.getName();
				jiuInkRecord.setSnName(snName);
				// 设置设备状态为关闭状态,因为设备开关不同步，需要手动设置值
				if (i == someink.size() - 1) {
					jiuInkRecord.setSnStatus("0");
				} else {
					jiuInkRecord.setSnStatus(someink.get(i).getSnStatus());
				}
				jiuInkRecord.setInkStatus(someink.get(i).getInkStatus());
				// 设置单价
				List<DataModel> dList = someink.get(i).getDatalist();
				List<JiuInk> inkList = jiuInkService.findBySn(someink.get(0).getSn());
				if (dList != null) {
					for (int j = 0; j < dList.size(); j++) {
						DataModel data = dList.get(j);
						if (inkList != null) {
							data.setFlag(inkList.get(j).getColor());
							data.setPrice(inkList.get(j).getPrice());
						}
					}
				}
				jiuInkRecord.setInkMessage(com.alibaba.fastjson.JSON.toJSONString(dList));
				jiuInkRecord.setOrderNo(orderLog.getOrderNo());
				jiuInkRecord.setSnName(jiuDeviceService.getBySn(orderLog.getDeviceSn()).getName());
				jiuInkRecord.setMemberId(jiuOrderRecordService.get(orderLog.getOrderId()).getMemberOpenId());
				// 将数据发送的时间-为记录的创建时间，实现数据顺序
				jiuInkRecord.setCreateTime(someink.get(i).getCreateTime());
				jiuInkRecordService.save(jiuInkRecord);
			}
		}

	}

	/***
	 * 
	 * @function: 登录 ,绑定手机号
	 * @param mobile
	 * @param code
	 * @param requests
	 * @param response
	 * @param model
	 */
	@ResponseBody
	@RequestMapping(value = "login", method = RequestMethod.POST)
	public String login(@RequestParam("mobile") String mobile, @RequestParam("code") String code,
			HttpServletRequest request, HttpServletResponse response, Model model) {
		String openId = getOpenId("userinfo_openid", request);

		if (StringUtils.isEmpty("mobile") && StringUtils.isEmpty(code)) {

			return JsonResult.Result(ResultCode.FAIL, "请正确填写手机号与验证码！");
		}

		MobileMessageRecorder mobileMessageRecorder = mobileMessageRecorderService.findByMobileAndCode(mobile, code);
		if (mobileMessageRecorder == null) {
			return JsonResult.Result(ResultCode.FAIL, "验证码错误！");
		}

		Date createTime = mobileMessageRecorder.getCreateTime();
		Long l = DateUtils.getMinute(new Date(), createTime);
		if (l.longValue() > 10) {
			return JsonResult.Result(ResultCode.FAIL, "验证码超时，请重新获取验证码！");
		}
		JiuWechatMember member = getMember(USER_ID, openId);
		if (member == null) {
			return JsonResult.Result(ResultCode.FAIL, "登录失败，请重新获取页面！");
		}
		member.setMobile(mobile);
		jiuWechatMemberService.save(member);

		request.getSession().setAttribute("mobile", mobile);
		return JsonResult.Result(ResultCode.SUCCESS, "登录成功！");

	}

	// 注册or登录 发送短信
	@ResponseBody
	@RequestMapping(value = "sendEditMobileSMS")
	public String sendEditMobileSMS(HttpServletResponse response, HttpServletRequest request, Model model) {
		Map<String, String> resultMap = new HashMap<String, String>();
		System.out.println("sendEditMobileSMS");
		String mobile = RequestUtil.getString(request, "mobile");
		if (StringUtils.isEmpty(mobile)) {
			return JsonResult.Result(ResultCode.FAIL, "请正确输入手机号！");
		}

		String openId = getOpenId("userinfo_openid", request);
		if (StringUtils.isEmpty(openId)) {

			return JsonResult.Result(ResultCode.FAIL, "页面已过期，请重新获取页面！");
		}
		JiuWechatMember member = getMember(USER_ID, openId);
		if (member == null) {

			return JsonResult.Result(ResultCode.FAIL, "页面已过期，请重新获取页面！");
		}

		MobileMessageRecorder message = mobileMessageRecorderService.findLostByMember(member.getId());

		if (message != null) {

			Long s = (System.currentTimeMillis() - message.getCreateTime().getTime()) / 1000;
			if (s < 60) {

				return JsonResult.Result(ResultCode.TOO_FREQUENT, "操作太频繁，请稍后再试！");
			}
		}

		// 生成随机码（验证码）
		String randnum = SMSUtils.getRandNum(6);
		System.out.println(randnum);

		Map<String, Object> map = SMSUtils.sendSMSByMap(mobile, randnum);
		MobileMessageRecorder mobileMessageRecorder = new MobileMessageRecorder();

		mobileMessageRecorder.setUser(UserUtils.getUserById(USER_ID));
		mobileMessageRecorder.setName(member.getName());
		mobileMessageRecorder.setMemberId(member.getId());
		mobileMessageRecorder.setMobile(mobile);
		mobileMessageRecorder.setRandNum(randnum);
		mobileMessageRecorderService.save(mobileMessageRecorder);

		if ("0".equals(map.get("error_code"))) {
			mobileMessageRecorder.setErrorMsg(
					"error_code:" + map.get("error_code").toString() + ";reason:" + map.get("reason").toString());
			mobileMessageRecorderService.save(mobileMessageRecorder);

			return JsonResult.Result(ResultCode.SUCCESS, "验证码已经发送到" + mobile + "手机，请注意查收！");
		} else {

			mobileMessageRecorder.setErrorMsg(
					"error_code:" + map.get("error_code").toString() + ";reason:" + map.get("reason").toString());

			mobileMessageRecorderService.save(mobileMessageRecorder);

			return JsonResult.Result(ResultCode.SUCCESS, "发送失败，请重新发送！");
		}
	}

	/**
	 * 查询微信订单
	 * 
	 * @param order
	 * @param request
	 * @return
	 */
	private Map<String, String> findPayUrlByJSAPI(String orderNO, HttpServletRequest request) {
		WXPay wxPay = wxPayService.getByUserId(USER_ID);
		if (wxPay == null) {
			request.setAttribute("message", "商户配置不正确！");
		} else {
			WeChat weChat = getWeChat(request, USER_ID);
			WxPayHelper wxPayHelper = new WxPayHelper();
			wxPayHelper.setApiKey(wxPay.getApiKey());
			wxPayHelper.setAppId(weChat.getAppId());
			wxPayHelper.setMchId(wxPay.getMchId());
			wxPayHelper.SetParameter("nonce_str", CommonUtil.CreateNoncestr());
			wxPayHelper.SetParameter("out_trade_no", orderNO);

			try {
				return wxPayHelper.findPayUrlByJSAPI();
			} catch (Exception e) {
				log.error(e.getMessage(), e);
			}
		}
		return null;
	}

	/**
	 * 根据USERID获取weChat
	 * 
	 * @param request
	 * @param user
	 * @return
	 */
	public WeChat getWeChat(HttpServletRequest request, Long userId) {
		WeChat weChat = (WeChat) CacheUtils.get("we_chat_" + userId);
		if (weChat == null) {
			weChat = weChatService.getWeChatByUserId(userId);
			CacheUtils.put("we_chat_" + userId, weChat);
		}
		return weChat;
	}

	public void getJsapiTicket(HttpServletRequest request, Long userId) {
		WeChat weChat = WechatCacheUtils.getWeChatByUserId(userId);
		String ticket = JsTicketUtils.getJSAPITicket(weChat);
		String url = request.getRequestURL() + "";
		if (request.getQueryString() != null) {
			url += "?" + request.getQueryString();
		}
		Map<String, String> result = new HashMap<String, String>();
		result = WechatInterfaceUtils.sign(ticket, url);
		request.setAttribute("signature", result.get("signature"));
		request.setAttribute("nonceStr", result.get("nonceStr"));
		request.setAttribute("timestamp", result.get("timestamp"));
		request.setAttribute("weChatAppId", weChat.getAppId());
	}

	/** 从缓存获取会员 */
	public JiuWechatMember getMember(Long uid, String openId) {

		JiuWechatMember member = (JiuWechatMember) CacheUtils.get(openId);
		if (member == null) {
			member = jiuWechatMemberService.getByUserIdAndOpenId(uid, openId);
			CacheUtils.put(openId, member);
		}
		return member;
	}

	/***
	 * 
	 * @function:
	 *            <p>
	 *            测试所用 上线需删除
	 *            </p>
	 */
	@RequestMapping("clear")
	public void del() {
		JedisUtils.del(JiuSn.DEVICE_EXSIT + "_" + "869696043668891");
		JedisUtils.del(JiuDevice.DEVICE_RUNTIME_KEY_PREFIX + "869696043668891");
	}

	/**
	 * 
	 * @function:
	 *            <p>
	 *            用户退出登录
	 *            </p>
	 * @param request
	 */
	@RequestMapping(value = "logout")
	public String logout(HttpServletRequest request, HttpServletResponse response) {
		String openId = getOpenId("userinfo_openid", request);
		if (StringUtils.isEmpty(openId)) {
			// 拉取授权
			System.err.println("拉取了授权方法===》" + openId);
			String url = WechatUtils.getOAuthUrl("/jiujiudevice/usercenter", USER_ID, request, response);
			return "redirect:" + url;
		}

		JiuWechatMember member = getMember(USER_ID, openId);
		if (member == null) {
			// 拉取授权
			System.err.println("拉取了授权方法===》" + openId);
			String url = WechatUtils.getOAuthUrl("/jiujiudevice/usercenter", USER_ID, request, response);
			return "redirect:" + url;
		}
		// 设置登录人的手机号为空，清空登录状态
		member.setMobile("");
		return "redirect:" + Global.FRONT_PATH + "/jiujiudevice/login";
	}
}
